package LeetCode.BucketSort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author : LdLtd
 * @Date : 2023/9/13
 * @Description:桶排序
 */
public class BucketSort {
    public static void bucketSort(int[] arr, int maxVal) {
        if (arr == null || arr.length == 0) {
            return;
        }

        // 创建桶
        List<Integer>[] buckets = new ArrayList[maxVal + 1];
        for (int i = 0; i <= maxVal; i++) {
            buckets[i] = new ArrayList<>();
        }

        // 将元素分配到桶中
        for (int num : arr) {
            buckets[num].add(num);
        }

        // 对每个桶中的元素进行排序
        for (int i = 0; i <= maxVal; i++) {
            Collections.sort(buckets[i]);
        }

        // 将排序后的元素放回原数组
        int index = 0;
        for (int i = 0; i <= maxVal; i++) {
            for (int num : buckets[i]) {
                arr[index++] = num;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 2, 9, 1, 5, 6};
        int maxVal = 9;

        System.out.println("原始数组：");
        printArray(arr);

        bucketSort(arr, maxVal);

        System.out.println("桶排序后的数组：");
        printArray(arr);
    }

    private static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
